package chat.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.orm.SugarRecord;
import com.whu.zj.MyApplication;
import com.whu.zj.R;
import com.whu.zj.UIHandler;

import java.util.ArrayList;
import java.util.List;

import chat.adapter.RoomMessageAdapter;
import chat.model.RoomChatModel;
import chat.network.http.SendRoomMessage;
import inter.ResponseStatus;
import model.MessageNotify;
import model.Room;
import model.RoomMessage;
import utils.TimeUtil;

/**
 * 群聊
 * Created by 凯 on 2015/10/31.
 */
public class RoomChatActivity extends UIHandler.BaseActivity {


    // 用户房间
    Room userRoom;

    // 标题栏
    TextView tv_title;

    // 群组用户
//    Button btn_groupuser;

    // 发送消息按钮
    Button btn_send;
    // 输入消息
    EditText et_message;
    // 显示消息
    ListView lv_message;

    // 刷新控件
    SwipeRefreshLayout swiperefresh;

    // 返回
    Button btn_back;

    RoomMessageAdapter roomMessageAdapter = new RoomMessageAdapter();

    List<RoomMessage> roomMessages = new ArrayList<RoomMessage>();

    RoomChatModel roomChatModel = new RoomChatModel();

    {
        roomChatModel.setRoomMessages(roomMessages);
        roomMessageAdapter.setRoomMessages(roomMessages);
        roomMessageAdapter.setRoomChatModel(roomChatModel);
    }

    SendRoomMessage sendRoomMessage = new SendRoomMessage();

    SendRoomMessage.Delegate sendRoomMessageResponse = new SendRoomMessage.Delegate() {
        @Override
        public void onResponse(String s, SendRoomMessage.RoomMessage roomMessage) {
            if (!s.startsWith("{"))return;
            Gson gson = new Gson();
            SendRoomMessage.ResponseMessageState responseMessageState = gson.fromJson(s, SendRoomMessage.ResponseMessageState.class);
            if (responseMessageState.getStatus().equals(ResponseStatus.SUCCESS))
            {
                Toast.makeText(MyApplication.share(),"发送成功",Toast.LENGTH_SHORT).show();
                save2roomessage(roomMessage);
                roomChatModel.getnew();
                roomMessageAdapter.notifyDataSetChanged();
                lv_message.smoothScrollToPosition(roomMessages.size()-1);

            }
        }

        @Override
        public void onError(VolleyError volleyError) {

        }
    };

    {
        sendRoomMessage.setDelegate(sendRoomMessageResponse);
    }


    RoomMessageReceiver roomMessageReceiver;

    // 保存至roommessage数据库
    private void save2roomessage(SendRoomMessage.RoomMessage m) {
        RoomMessage roomMessage = new RoomMessage();
        roomMessage.setRm_Content(m.getRm_Content());
        roomMessage.setRm_Time(m.getRm_Time());
        roomMessage.setRm_Type(m.getRm_Type());
        roomMessage.setRoomid(m.getRoom_ID());
        roomMessage.setUser_ID(m.getUser_ID());
        roomMessage.setUser_RealName(MyApplication.getOwnUser().getUser_RealName());
        roomMessage.setRoom_Name(userRoom.getRoom_Name());
        SugarRecord.save(roomMessage);

        // 更新未读消息条目
        List<MessageNotify> messages = SugarRecord.find(MessageNotify.class,"nameid = ? and type = ?",m.getRoom_ID(),"5");
        if (!messages.isEmpty())
        {
            MessageNotify messageNotify = messages.get(0);
            messageNotify.setContent("我:"+m.getRm_Content());
            messageNotify.setTime(m.getRm_Time());
            SugarRecord.save(messageNotify);
        }
        else
        {
            MessageNotify messageNotify = new MessageNotify();
            messageNotify.setTime(m.getRm_Time());
            messageNotify.setContent("我:" + m.getRm_Content());
            messageNotify.setNameid(m.getRoom_ID());
            messageNotify.setRealName(userRoom.getRoom_Name());
            messageNotify.setType("5");
            SugarRecord.save(messageNotify);
        }

    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_groupchat);

        initview();
        initdata();

    }

    // 初始化数据
    private void initdata() {
        userRoom = (Room) getIntent().getSerializableExtra("userRoom");
        tv_title.setText(userRoom.getRoom_Name());
        roomChatModel.setRoomId(userRoom.getRoom_ID() + "");
        roomChatModel.init();
        roomMessageAdapter.notifyDataSetChanged();

        lv_message.smoothScrollToPosition(roomMessages.size()-1);


    }

    View.OnClickListener itemClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_send) {
                send();
                et_message.setText("");
            }
            else if (v == btn_back) {
                finish();
            }
        }
    };

    // 发送消息
    private void send() {
        String message = et_message.getText().toString();
        if (message.equals("")) {
            return;
        }

        SendRoomMessage.RoomMessage roomMessage = new SendRoomMessage.RoomMessage();
        roomMessage.setUser_ID(MyApplication.getOwnUser().getUser_ID());
        roomMessage.setRoom_ID(userRoom.getRoom_ID() + "");
        roomMessage.setRm_Type("text");
        roomMessage.setRm_Content(message);
        roomMessage.setRm_Time(TimeUtil.currentTime());
        sendRoomMessage.setRoomMessage(roomMessage);
        sendRoomMessage.send();
    }

    // 初始化界面
    private void initview() {
        tv_title = (TextView) findViewById(R.id.id_tv_title);
        tv_title.setText("");

//        btn_groupuser = (Button) findViewById(R.id.id_btn_groupusers);
//        btn_groupuser.setOnClickListener(itemClick);

        btn_send = (Button) findViewById(R.id.id_btn_send);
        btn_send.setOnClickListener(itemClick);

        et_message = (EditText) findViewById(R.id.id_et_message);
        lv_message = (ListView) findViewById(R.id.id_message);


        lv_message.setAdapter(roomMessageAdapter);


        swiperefresh = (SwipeRefreshLayout) findViewById(R.id.id_id_refresh);
        swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                int num = roomChatModel.getold();
                roomMessageAdapter.notifyDataSetChanged();
                swiperefresh.setRefreshing(false);
                lv_message.smoothScrollToPosition(num);
            }
        });

        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(itemClick);

        roomMessageReceiver = new RoomMessageReceiver();
        IntentFilter intentFilter = new IntentFilter("com.whu.zj.RoomMessage");
        registerReceiver(roomMessageReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(roomMessageReceiver);
    }

    @Override
    protected void onPause() {
        super.onPause();
        clearUnreadMessage();
    }

    // 清除未读消息数目
    private void clearUnreadMessage() {
        List<MessageNotify> messages = SugarRecord.findWithQuery(MessageNotify.class,"Select * from MessageNotify where nameid = ? and type = ?",userRoom.getRoom_ID()+"","5");
        if (!messages.isEmpty())
        {
            MessageNotify messageNotify = messages.get(0);
            messageNotify.setUnread("0");
            SugarRecord.save(messageNotify);
        }
    }

    // 监听房间消息通知
    class RoomMessageReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            roomChatModel.getnew();
            roomMessageAdapter.notifyDataSetChanged();
            lv_message.smoothScrollToPosition(roomMessages.size()-1);
        }
    }
}
